package com.ndood.gateway.app.security.handler;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ndood.api.base.constaints.ApiCode;
import com.ndood.gateway.base.pojo.GatewayResultVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;

@Component("unAuthenticatedAccessHandler")
@Slf4j
public class PaymentUnAuthenticatedAccessHandler implements AuthenticationEntryPoint{

	@Autowired
	private ObjectMapper objectMapper;

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {
	
		// 根据配置进行处理
		// response.setStatus(HttpStatus.UNAUTHORIZED.value());
		response.setStatus(HttpStatus.OK.value());
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers",
				"x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");
		response.setContentType("application/json;charset=UTF-8");
		
		System.out.println(request.getRequestURL());
		String json = objectMapper.writeValueAsString(
				GatewayResultVo.error().setCode(ApiCode.ERR_TOKEN.getCode()).setMsg(exception.getMessage()));

		StringBuilder sb = new StringBuilder("\n");
		sb.append("CCCCCCCCCCCCCCC需要登录才能访问该资源CCCCCCCCCCCCCCC").append("\n");
		sb.append(JSON.toJSON(getHeadersInfo(request))).append("\n");
		sb.append(JSON.toJSON(request.getParameterMap())).append("\n");
		sb.append("返回结果:").append(json).append("\n");
		sb.append("CCCCCCCCCCCCCCC需要登录才能访问该资源CCCCCCCCCCCCCCC").append("\n\n");
		log.error(sb.toString(), exception);
		
		response.getWriter().write(json);
		response.getWriter().flush();
	}
	
	/**
	 * 获取请求头信息
	 */
	private Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }	
	
}
